import { DataTypes, Model } from "sequelize";
import bcrypt from "bcryptjs";
import sequelize from "../config/database";
import Role from "./role.model";

interface UserAttributes {
  id: string;
  username: string;
  password: string;
  email: string;
  roleId: number;
  roule?: Role;
  comparePassword?: (password: string) => Promise<boolean>;
}

class User extends Model<UserAttributes> implements UserAttributes {
  public id!: string; // 主键，自动生成的 UUID
  public username!: string; // 用户名，字符串类型
  public password!: string; // 密码，字符串类型
  public email!: string; // 邮箱，字符串类型
  public roleId!: number; // 角色ID，整数类型
  public role?: Role; // 角色，关联的 Role 模型实例

  public comparePassword(password: string): Promise<boolean> {
    return bcrypt.compare(password, this.password);
  }
}

User.init(
  {
    id: {
      type: DataTypes.UUID,
      primaryKey: true,
      allowNull: false,
      autoIncrement: true,
    },
    username: {
      type: DataTypes.STRING(32),
      unique: true,
      allowNull: false,
      validate: {
        len: [3, 32],
      },
    },
    password: {
      type: DataTypes.STRING(128),
      allowNull: false,
      validate: {
        len: [6, 128],
      },
      set(value: string) {
        const hash = bcrypt.hashSync(value, 10);
        this.setDataValue("password", hash);
      },
    },
    email: {
      type: DataTypes.STRING(128),
      unique: true,
      allowNull: false,
      validate: {
        isEmail: true,
      },
    },
    roleId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 3, // 默认值为 3，即普通用户
    },
  },
  {
    sequelize,
    modelName: "User",
    tableName: "users",
  }
);

User.belongsTo(Role, { foreignKey: "roleId", as: "role" }); // 关联 Role 模型
Role.hasMany(User, { foreignKey: "roleId", as: "users" }); // 关联 User 模型
export default User;
